package com.sky.handler;

import com.sky.constant.MessageConstant;
import com.sky.exception.BaseException;
import com.sky.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

import static com.sky.constant.MessageConstant.ACCOUNT_EXITED;
import static com.sky.constant.MessageConstant.UNKNOWN_ERROR;

/**
 * 全局异常处理器，处理项目中抛出的业务异常
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 捕获业务异常
     * @param ex
     * @return
     */
    @ExceptionHandler
    public Result exceptionHandler(BaseException ex){
        log.error("异常信息：{}", ex.getMessage());
        return Result.error(ex.getMessage());
    }

    /**
     * 全局sql异常处理器
     * 统一捕获控制台中的sql异常
     * @param ex
     * @return
     */
    @ExceptionHandler
    public Result exceptionHandler(SQLIntegrityConstraintViolationException ex){
        //1. 获取错误信息
        String message = ex.getMessage();
        //2. 判断是否是重复添加错误
        if (message.contains("Duplicate entry")){
            //3. 提示前端用户已添加
            String[] split = message.split(" ");
            String name = split[2].replace("'","");
            String errorMsg=name+ ACCOUNT_EXITED;
            return Result.error(errorMsg);
        }else {
            return Result.error(UNKNOWN_ERROR);
        }
    }
}
